import { Injectable } from '@nestjs/common';
import { CreateClassroomDto } from './dto/create-classroom.dto';
import { UpdateClassroomDto } from './dto/update-classroom.dto';
import { Repository } from 'typeorm';
import { Classroom } from './entities/classroom.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { PageClassroomDto } from './dto/page-classroom.dto';
import { PageResult } from '../common/dto/common.page-result';

@Injectable()
export class ClassroomService {
  constructor(
    @InjectRepository(Classroom)
    private readonly classroomRepository: Repository<Classroom>,
  ) {
  }

  create(createClassroomDto: CreateClassroomDto) {
    this.classroomRepository.save(createClassroomDto);
  }

  async findAll() {
    return await this.classroomRepository.find();
  }

  async findOne(id: number) {
    return await this.classroomRepository.find({ where: { id: id } });
  }

  async update(id: number, updateClassroomDto: UpdateClassroomDto) {
    await this.classroomRepository.update(id, updateClassroomDto);
  }

  async remove(id: number) {
    const classroom = await this.findOne(id);
    if (classroom) {
      await this.classroomRepository.remove(classroom);
    } else {
      throw new Error('删除教室失败');
    }
  }

  async page(pageClassroomDto: PageClassroomDto) {
    const query = this.classroomRepository.createQueryBuilder('classroom');
    if (pageClassroomDto.name) {
      query.andWhere('classroom.name like :name', { name: `%${pageClassroomDto.name}%` });
    }
    if (pageClassroomDto.status) {
      query.andWhere('classroom.status = :status', { status: pageClassroomDto.status });
    }

    const [list, total] = await query
      .skip((pageClassroomDto.page - 1) * pageClassroomDto.size)
      .take(pageClassroomDto.size)
      .getManyAndCount();

    return new PageResult(
      pageClassroomDto.page,
      pageClassroomDto.size,
      total,
      list,
    );
  }

  /**
   * 状态修改
   * @param id 主键
   * @param status 状态
   * @returns 
   */
  async changeStatus(id: number, status: number) {
    return await this.classroomRepository.update(id, { status: status });
  }
}
